/**
 * amazonSOdetails.js
 *
 * @NAmdConfig ./configuration.json
 * @NApiVersion 2.x
 */
define(['N/record', 'N/search', '../common/utils', '../common/moment'],
    function (record, search, utils, moment) {
        var attribute = new Object();
        var method = new Object();
        // attribute.formId = 130;
        //attribute.defaultCustomerId = 63235;
        attribute.platform = 1;
        // attribute.defaultShipPriceItem = 5414;
        // attribute.defaultShipDiscountItem = 5412;
        // attribute.defaultPromotionDiscountItem = 5413;

        //所有的idMap, 上级节点都是order.
        //order主体
        attribute.orderIdMap_value = {
            "taxAmount": "taxamount"
        };
        attribute.orderIdMap_text = {
            "orderId": "custbody_platform_order_id",
            "totalAmount": "custbody_platform_total_amount",
            "customer.email": "custbody_customer_email"
        };
        attribute.orderExistsCondition = ["orderId"];
        //customer主体
        attribute.customerIdMap_value = {
            "customer.name": "name",
            "customer.email": "email",
            "customer.subsidiary": "subsidiary"
        };
        attribute.customerIdMap_text = {};
        attribute.customerExistsCondition = ["customer.email"];
        //item
        attribute.itemIdMap_value = {
            "lineId": "custcol_platform_item_line_id",
            //"itemTax":"taxamount",
            "description": "description",
            "itemTax": "custcol_platform_tax_amount"
        };
        attribute.itemIdMap_text = {};
        //address
        attribute.addressIdMap_value = {
            "customer.address.country": "country",
            "customer.address.state": "state",
            "customer.address.addressee": "addressee",
            "customer.address.city": "city",
            "customer.address.zip": "zip",
            "customer.address.phone": "addrphone",
            "customer.address.addressLine1": "addr1"
        };
        attribute.addressIdMap_text = {};
        attribute.addressExistsCondition = ["customer.address.addressLine1"];


        method.init = function (order) {
            var marketplaceId = order.marketplaceId;
            var sellerId = order.sellerId;
            var fulfillmentChannel = order.fulfillmentChannel;

            var email = order.customer.email;
            var name = order.customer.name;
            //顾客邮箱
            if (email === '' || email === null) {
                order.customer.email = 'amazon' + new Date().getTime() + '@marketplace.amazon.com'
            }
            //顾客名字
            if (name === '' || name === null) {
                var index = order.customer.email.indexOf("@");
                if (index !== -1) {
                    order.customer.name = order.customer.email.substring(0, index);
                } else {
                    order.customer.name = 'amazon' + new Date().getTime();
                }
            }
            var params = {
                "sellerId": sellerId,
                "marketplaceId": marketplaceId
            };
            var storeInformation = utils.method.store.getStoreInformation(params);

            if (!storeInformation.internalid) {
                throw " your store information is not exists in NETSUITE . marketplaceId : [" + marketplaceId + "] sellerId : [" + sellerId + "]";
            }
            order.storeId = storeInformation.internalid;
            order.storeName = storeInformation.name;
            order.storeCode = storeInformation.storeCode;
            order.storeCountryCode = storeInformation.storeCountryCode;
            //自动选择仓库和客户
            order.locationId = storeInformation.locationId;
            if (!order.currency) {
                order.currency = "USD";
            }
            //拿到所有税额
            var items = order.items;
            var taxAmount = 0;
            for (var i = 0; i < items.length; i++) {
                try {
                    taxAmount += items[i].itemTax;
                } catch (e) {
                }
            }
            order.taxAmount = taxAmount;
        }
        //自定义订单
        method.orderCustoming = function (rec, order) {
            var marketplaceId = order.marketplaceId;
            var sellerId = order.sellerId;
            var currencyName = order.currency;
            //平台来源
            rec.setValue('custbody_platform_source', attribute.platform);
            //订单写入各种时间开始
            try {
                if (order.purchaseTime) {
                    rec.setValue('trandate', new Date(order.purchaseTime));
                    rec.setValue('custbody_platform_payment_date',
                        new Date(order.purchaseTime));
                }
                if (order.lastShipTime) {
                    rec.setValue('custbody_platform_ship_date',
                        new Date(order.lastShipTime));
                }
                if (order.lastDeliveryTime) {
                    rec.setValue('custbody_platform_delivery_date',
                        new Date(order.lastDeliveryTime));
                }
            } catch (e) {
                throw e.message;
            }
            //服务级别
            var serviceLevel = order.serviceLevel;
            serviceLevel = '[amazon]' + serviceLevel;
            rec.setText('custbody_platform_service_level', serviceLevel);
            //选择订单币种
            rec.setValue('currency', Number(utils.method.getCurrencyIdByName(currencyName)));
            //订单状态
            //PartiallyShipped:Unshipped:Shipped
            /* if(order.status == "Shipped"){
                 rec.setValue('orderstatus','B');
             }else if(order.status == "Unshipped"){*/
            rec.setValue('orderstatus', 'B');
            /* }else{
                 rec.setValue('orderstatus','B');
             }*/
            //自动选择通道  "FBA"  "FBM"
            var fulfillmentChannel = order.fulfillmentChannel;
            if (fulfillmentChannel && fulfillmentChannel == 'AFN') {
                rec.setText('custbody_amz_fulfillment_channel', 'AFN');
            } else if (fulfillmentChannel && fulfillmentChannel == 'MFN') {
                rec.setText('custbody_amz_fulfillment_channel', 'MFN');
            }
            //自动选择店铺
            rec.setValue('custbody_platform_store', order.storeId);
            //自动选择仓库
            rec.setValue('location', Number(order.locationId));

            return order;
        }

        //自定义客户方法
        method.customerCustoming = function (order) {
            order.customer.subsidiary = 3;
            return order;
        }

        //自定义商品行
        method.itemLineCustoming = function (order) {
            var items = order.items;

            var afterinitItems = [];

            var itemNotFoundMSG = "";

            for (var i = 0; i < items.length; i++) {
                // items[i].sku = items[i].sku + '(' + order.storeCode + ')';

                //没有价格金额给0
                if (!items[i].amount) {
                    items[i].amount = 0.00;
                }

                var itemSearch = search.create({
                    type: 'kititem',
                    filters: ['name', 'is', items[i].sku]
                }).run().each(function (ctx) {
                    items[i].id = Number(ctx.id);
                });
                if (!items[i].id) {
                    itemNotFoundMSG += "platform seller sku [" + items[i].sku + "] not in Netsuite;\r\n";
                }

                afterinitItems.push(items[i]);
                //运费商品
                if (items[i].shipPrice) {
                    var shipItem = new Object();
                    shipItem.id = attribute.defaultShipPriceItem;
                    shipItem.amount = items[i].shipPrice;
                    shipItem.quantity = 1;
                    shipItem.description = "for " + items[i].sku;
                    afterinitItems.push(shipItem);
                }
                //运费折扣
                if (items[i].shipDiscount) {
                    var shipItem = new Object();
                    shipItem.id = attribute.defaultShipDiscountItem;
                    shipItem.amount = 0 - items[i].shipDiscount;
                    shipItem.quantity = 1;
                    shipItem.description = "for " + items[i].sku;
                    afterinitItems.push(shipItem);
                }
                //活动折扣
                if (items[i].discount) {
                    var shipItem = new Object();
                    shipItem.id = attribute.defaultPromotionDiscountItem;
                    shipItem.amount = 0 - items[i].discount;
                    shipItem.quantity = 1;
                    shipItem.description = "for " + items[i].sku;
                    afterinitItems.push(shipItem);
                }
            }

            if (itemNotFoundMSG != "") {
                throw itemNotFoundMSG;
            }
            return afterinitItems;
        }

        //地址自定义方法
        method.addressCustoming = function (order) {
            return order;
        }

        return {
            method: method,
            attribute: attribute
        };
    });